#include "core_task.h"
CoreTask::CoreTask()
{
}


CoreTask::~CoreTask()
{
}

void CoreTask::addTask(Task task)
{
	std::lock_guard<std::mutex> lock(mymutex);
	this->_tasksBuf.push_back(task);
}

void CoreTask::start()
{
	cthread.start("core_task", nullptr, [this](CoreThread* pthread) {
		this->onRun(pthread);
		}, nullptr);
}

void CoreTask::stop()
{
	cthread.stop();
}

void CoreTask::onRun(CoreThread* pthread)
{
	while (pthread->running())
	{
		if (!this->_tasksBuf.empty())
		{
			std::lock_guard<std::mutex> lock(mymutex);
			for (auto task:this->_tasksBuf)
			{
				this->_tasks.push_back(task);
			}
			this->_tasksBuf.clear();
		}
		if (this->_tasks.empty())
		{
			std::chrono::milliseconds t(1);
			std::this_thread::sleep_for(t);
			continue;
		}
		for (auto pTask : this->_tasks)
		{
			pTask();
		}
		this->_tasks.clear();
	}
	for (auto pTask : this->_tasksBuf)
	{
		pTask();
	}
}
